package com.zzyl.nursing.service.impl;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Resource
    private ElderMapper elderMapper;
    @Resource
    private BedMapper bedMapper;
    @Resource
    private ContractMapper contractMapper;
    @Resource
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 查询入住详情
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo detailVo = new CheckInDetailVo();
        //1.查询入住详情
        CheckIn checkIn = getById(id);
        String remark = checkIn.getRemark();
        //更具身份证号码计算年龄
        int age = calculateAge(checkIn.getIdCardNo());
        //2.查询老人信息
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        checkInElderVo.setAge(age);
        detailVo.setCheckInElderVo(checkInElderVo);
        //3查询合同
        Contract contract = contractMapper.selectContract(elderId);
        detailVo.setContract(contract);
        //4.查询入住配置checkInConfigVo
        CheckInConfig config = checkInConfigMapper.selectConfig(id);
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        BeanUtils.copyProperties(config, checkInConfigVo);
        detailVo.setCheckInConfigVo(checkInConfigVo);
        //5.转换家属列表
        ObjectMapper objectMapper = new ObjectMapper();
        //[{"kinship":"0","name":"李天","phone":"13222334439"}]
        try {
            List<ElderFamilyVo> list = objectMapper.readValue(remark, objectMapper.getTypeFactory().constructCollectionType(List.class, ElderFamilyVo.class));
            detailVo.setElderFamilyVoList(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回数据
        return detailVo;
    }

    /**
     * //更具身份证号码计算年龄
     *
     * @param idCardNo
     * @return
     */
    private int calculateAge(String idCardNo) {
        try {
            // 提取出生日期
            String birthDateStr = idCardNo.substring(6, 14);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            Date birthDate = sdf.parse(birthDateStr);
            // 获取当前日期
            Calendar currentCal = Calendar.getInstance();
            Calendar birthCal = Calendar.getInstance();
            birthCal.setTime(birthDate);
            int age = currentCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
            // 检查是否已经过了生日
            if (currentCal.get(Calendar.DAY_OF_YEAR) < birthCal.get(Calendar.DAY_OF_YEAR)) {
                age--;
            }
            return age;
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 申请入住
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        //1.判断老人是否已入住，如果已入住抛出异常
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo());
        elderWrapper.in(Elder::getStatus, 0, 1, 2, 3, 4);
        Elder elder = elderMapper.selectOne(elderWrapper);
        if (elder != null) {
            throw new BaseException("该老人已入住，请勿重复入住");
        }
        //2.更新床位状态为已入住
        Bed bed = bedMapper.selectBedById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人（对已经离开后又回来入住的老人需要更新，否则插入）
        Elder elder1 = updateOrInsertElder(dto.getCheckInElderDto(), bed);
        //4.新增签约办理（合同数据）
        insertContract(dto, elder1);
        //5.新增入住记录
        CheckIn checkIn = insertCheckIns(dto, elder1);
        //6.新增入住配置
        insertCheckInConfig(dto.getCheckInConfigDto(), checkIn.getId());
    }

    /**
     * //6.新增入住配置
     *
     * @param checkInConfigDto
     * @param id
     */
    private void insertCheckInConfig(CheckInConfigDto checkInConfigDto, Long id) {
        CheckInConfig config = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, config);
        config.setCheckInId(id);
        checkInConfigMapper.insert(config);
    }

    /**
     * //5.新增入住记录
     */
    private CheckIn insertCheckIns(CheckInApplyDto dto, Elder elder1) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder1.getId());
        checkIn.setElderName(elder1.getName());
        checkIn.setIdCardNo(elder1.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder1.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * //4.新增签约办理（合同数据）
     *
     * @param dto
     * @param elder1
     */
    private void insertContract(CheckInApplyDto dto, Elder elder1) {
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder1.getId());
        contract.setElderName(elder1.getName());
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);
        LocalDateTime endDate = dto.getCheckInConfigDto().getEndDate();
        contract.setEndDate(endDate);
        //合同状态
        Integer status = startDate.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人（对已经离开后又回来入住的老人需要更新，否则插入）
     */
    private Elder updateOrInsertElder(CheckInElderDto checkInElderDto, Bed bed) {
        //拷贝老人信息
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        //1.判断老人是否已存在，存在则更新，不存在则插入
        LambdaQueryWrapper<Elder> elderWrapper = new LambdaQueryWrapper<>();
        elderWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo());
        elderWrapper.eq(Elder::getStatus, 5);
        Elder elderDo = elderMapper.selectOne(elderWrapper);
        if (elderDo != null) {
            //1.1更新老人信息
            elderMapper.updateById(elder);
        } else {
            //1.2插入老人信息
            elderMapper.insert(elder);
        }
        return elder;
    }
}
